package delayQueue;


import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayQueueElement implements Delayed {
    //任务过期时间
    private long removeTime;
    //任务
    private DelayTask task;

    public DelayQueueElement(long timeout, TimeUnit unit, DelayTask delayTask) {
        this.task = delayTask;
        this.removeTime = System.currentTimeMillis()+unit.toMillis(timeout);
    }

    public DelayTask getTask() {
        return task;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(removeTime-System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        if (o == null) return 1;
        if (getDelay(TimeUnit.MILLISECONDS) > o.getDelay(TimeUnit.MILLISECONDS)){
            return 1;
        }else if (getDelay(TimeUnit.MILLISECONDS) == o.getDelay(TimeUnit.MILLISECONDS)){
            return 0;
        }else {
            return -1;
        }
    }
}
